package com.seahorse.youliao.util;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

/**
 * @ProjectName: youliao
 * @Package: com.seahorse.youliao.util
 * @ClassName: SecurityUtils
 * @Description: Security相关操作
 * @author:songqiang
 * @Date:2020-01-10 9:55
 **/
public class SecurityUtils {

    /**
     * 获取当前用户名
     * @return
     */
    public static String getUsername() {
        String username = null;
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if(authentication != null) {
            Object principal = authentication.getPrincipal();
            if(principal instanceof UserDetails){
                username = ((UserDetails) principal).getUsername();
            }else{
                // 认证principal 为用户名
                username = principal.toString();
            }
        }
        return username;
    }

    /**
     * 获取用户名
     * @return
     */
    public static String getUsername(Authentication authentication) {
        String username = null;
        if(authentication != null) {
            Object principal = authentication.getPrincipal();
            if(principal != null && principal instanceof UserDetails) {
                username = ((UserDetails) principal).getUsername();
            }else{
                username = principal.toString();
            }
        }
        return username;
    }


}
